package com.demo.lengthFieldBasedFrameDecoder.demo2;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.MessageToByteEncoder;
import java.nio.charset.Charset;

/**
 * lenth 签名有其他的字端数 和demo1区别是,真里面有，还有其他字节数，
 */
public class NewClient {
    private  int port;
    private  String address;
    public NewClient(int port,String address) {
        this.port = port;
        this.address = address;
    }
    public void start(){
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new NewClientChannelInitializer());
        try {
            ChannelFuture future = bootstrap.connect(address,port).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
    public static void main(String[] args) {
        NewClient client = new NewClient(7788,"127.0.0.1");
        client.start();
    }
    public class NewClientChannelInitializer extends ChannelInitializer<SocketChannel> {
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            ChannelPipeline pipeline = socketChannel.pipeline();
            pipeline.addLast(new NewEncoder());
            pipeline.addLast(new NewClientHandler());
        }
    }

    static class NewEncoder extends MessageToByteEncoder<Message> {
        @Override
        protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
            if(message == null){
                throw new Exception("未获得消息内容");
            }
            String msgBody = message.getMsgBody();
            byte[] b = msgBody.getBytes(Charset.forName("utf-8"));
            byteBuf.writeByte(message.getType());
            byteBuf.writeByte(b.length);//长度1个字节感觉数量太小了。1个字节对应长度太少了
            byteBuf.writeBytes(b);
        }
    }
    static class NewClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            String m = "你好啊,Netty。昂昂";
            Message msg = new Message((byte)0xCA, m.length(), m);
            ctx.writeAndFlush(msg);
        }
    }
}